/**
 * 
 */
package it.unitn.testbed.server.serial;

import org.apache.log4j.Logger;

/**
 * A serial message consumer that logs messages.
 * 
 * @author Stefan Guna
 * 
 */
public class LogMsgConsumer implements MessageConsumer {
	public static Logger log = Logger.getLogger(LogMsgConsumer.class.getName());

	/*
	 * (non-Javadoc)
	 * 
	 * @see it.unitn.testbed.server.serial.MessageConsumer#beginMessage(int,
	 * java.lang.String)
	 */
	public Object beginMessage(int moteId, String type) {
		StringBuffer buf = new StringBuffer();
		buf.append("[" + moteId + "] " + type + ": ");
		return buf;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * it.unitn.testbed.server.serial.MessageConsumer#endMessage(java.lang.Object
	 * )
	 */
	public void endMessage(Object context) {
		StringBuffer buf = (StringBuffer) context;
		log.info(buf.toString());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * it.unitn.testbed.server.serial.MessageConsumer#field(java.lang.Object,
	 * java.lang.String, java.lang.Object)
	 */
	public void field(Object context, String fieldName, Object fieldValue) {
		StringBuffer buf = (StringBuffer) context;
		if (fieldValue instanceof Integer) {
			buf.append(fieldName + "=" + (Integer) fieldValue);
			return;
		}
		if (fieldValue instanceof Short) {
			buf.append(fieldName + "=" + (Short) fieldValue);
			return;
		}
		try {
			if (Class.forName("[I").isInstance(fieldValue)) {
				buf.append(fieldName + "= [");
				int values[] = (int[]) fieldValue;
				for (int i = 0; i < values.length - 1; i++)
					buf.append(values[i] + ", ");
				buf.append("]");
			}
		} catch (ClassNotFoundException e) {
			log.error(e.getMessage());
		}
		try {
			if (Class.forName("[S").isInstance(fieldValue)) {
				buf.append(fieldName + "= [");
				short values[] = (short[]) fieldValue;
				for (int i = 0; i < values.length - 1; i++)
					buf.append(values[i] + ", ");
				buf.append("]");
			}
		} catch (ClassNotFoundException e) {
			log.error(e.getMessage());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * it.unitn.testbed.server.serial.MessageConsumer#newMessageType(java.lang
	 * .String, it.unitn.testbed.server.serial.FieldType[])
	 */
	public void newMessageType(String type, FieldType[] fieldType) {
		log.info("New message type: " + type);
		for (int i = 0; i < fieldType.length; i++)
			log.info("  field: " + fieldType.toString());
	}
}
